package com.example.mongodb.mongodb.controller.rabbitmq.direct;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 使用direct 模式的交换机
 * 交换机直接与routingKey绑定
 * 消费者也申明交换机与routingKey绑定并绑定随机队列就可以消费
 */
public class directDemo2 {
    public static void main(String[] args) {

        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("123.207.179.78");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");


        try {
            Connection connection = connectionFactory.newConnection();
            Channel channel = connection.createChannel();


            //申明一个direct 模式的交换机
            channel.exchangeDeclare("direct_logs", BuiltinExchangeType.DIRECT);

            // 定义路由键
            String servity = null;
            for (int i = 0; i <= 100; i++) {
                switch (i % 3) {
                    case 0:
                        servity = "info";
                        break;
                    case 1:
                        servity = "warn";
                        break;
                    case 2:
                        servity = "error";
                        break;
                    default:
                        System.out.println("log错误，程序退出");
                        System.exit(-1);
                }


                String logStr = "这是一个 【" + servity + "】的消息";

                // String exchange, String routingKey, BasicProperties props, byte[] body
                channel.basicPublish("direct_logs", servity, null, logStr.getBytes("UTF-8"));
            }

        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }


    }
}
